package top.glkj.hms.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.glkj.hms.entity.User;
import top.glkj.hms.service.CodeService;
import top.glkj.hms.service.UserService;
import top.glkj.hms.utils.Result;
import top.glkj.hms.utils.ResultFactory;

import javax.annotation.security.PermitAll;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/8/28 13:14
 * 认证接口
 */
@Api(tags = "认证管理")
@RestController
@RequestMapping("/auth")
public class AuthController {
    private final CodeService codeService;
    private final UserService userService;
    @Autowired
    public AuthController(CodeService codeService, UserService userService) {
        this.codeService = codeService;
        this.userService = userService;
    }

    @ApiOperation("获取验证码图片")
    @PermitAll
    @RequestMapping(value = "/getCode/{id}")
    public Result makeImage(HttpServletRequest request, HttpServletResponse response, @PathVariable(name = "id") Long id) throws IOException {
        // 图片输出 ImageIO
        response.setContentType("image/jpg");
        ImageIO.write(codeService.getCode(id).getBufferedImage(), "JPEG", response.getOutputStream());
        return ResultFactory.SUCCESS;
    }

    @ApiOperation("获取用户详细信息")
    @PostMapping
    public Result getUserInfo() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userService.getOne(principal.getId());
    }
}
